package com.itheima.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.itheima.common.SmsResponse;


/**
 * @version V1.0
 * @author: yongjichu
 * @date: 2020/1/18 15:15
 * @description:
 */
public class SmsUtil {
    public static SmsResponse sendSmsCode(String phoneNumbers,String code){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                //阿里云的密钥
                "LTAI4FokWLEfr4t4pS3ctZHN",
                //阿里云的密钥
                "NfNS2tfIfFatb4El2f1rJWaf05TdNK");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        //这里的手机号是从前端传过来的，所以要从参数里获取
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", "传智健康");
        request.putQueryParameter("TemplateCode", "SMS_182672116");
        //这个code参数（及验证码）也是从前端传过来的，因为参数需要的是json字符串，我们首先把参数code变成json字符串
        //注意使用alibaba的fastjson转换
        JSONObject param = new JSONObject();
        param.put("code",code);
        request.putQueryParameter("TemplateParam", param.toJSONString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            //response.getData()打印的结果为{"Message":"OK","RequestId":"4D867847-396E-4743-ACE1-4B4109477FCB","BizId":"221416179334842586^0","Code":"OK"}
            //封装一个pojo封装以上的数据SmsResponse
            //把以上的json形式转换为字符串
            SmsResponse smsResponse = JSONObject.parseObject(response.getData(), SmsResponse.class);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        sendSmsCode("15150466527","2334");

    }
}
